package iloc.cc.tablelayoutdemo;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;


public class SimpleFragmentPagerAdapter extends FragmentPagerAdapter {
	private FragmentManager fragmentManager;
	private String[] tabTitles = null;
	//这个地方一定要自己new
	private List<Fragment> fragments = new ArrayList<>();

	public SimpleFragmentPagerAdapter(FragmentManager fm,
									  List<Fragment> fragments, String[] tabTitles) {
		super(fm);
		this.fragmentManager = fm;
		//
		this.fragments.addAll(fragments);
		this.tabTitles = tabTitles;
	}

	@Override
	public Fragment getItem(int position) {
		if (position < fragments.size()) {
			return fragments.get(position);
		}
		return null;
	}

	@Override
	public int getCount() {
		return fragments.size();
	}

	@Override
	public CharSequence getPageTitle(int position) {
		if (tabTitles != null && position < tabTitles.length) {
			return tabTitles[position];
		}

		return super.getPageTitle(position);
	}

	@Override
	public Object instantiateItem(ViewGroup container, int position) {

		return super.instantiateItem(container, position);
	}

	@SuppressWarnings("SuspiciousMethodCalls")
	@Override
	public int getItemPosition(Object object) {
		 if (!fragments.contains(object)) {
			 return POSITION_NONE;
		 }
		return super.getItemPosition(object);
	}

	public void setTabTitles(String[] tabTitles) {
		this.tabTitles = tabTitles;
	}

	public List<Fragment> getFragments() {
		return fragments;
	}

	public void setFragments(List<Fragment> fragments) {
		if (this.fragments != null) {
			FragmentTransaction ft = fragmentManager.beginTransaction();
			for (Fragment f : this.fragments) {
				ft.remove(f);
			}
			ft.commit();
			fragmentManager.executePendingTransactions();
		}
		//
		this.fragments.clear();
		this.fragments.addAll(fragments);
		notifyDataSetChanged();
	}
}
